package org.spring.aicloud.controller;

import com.alibaba.cloud.ai.tongyi.chat.TongYiChatClient;
import com.alibaba.cloud.ai.tongyi.chat.TongYiChatOptions;
import com.alibaba.cloud.ai.tongyi.image.TongYiImagesClient;
import com.alibaba.cloud.ai.tongyi.image.TongYiImagesOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.spring.aicloud.entity.Answer;
import org.spring.aicloud.entity.enums.AIModelEnum;
import org.spring.aicloud.entity.enums.AITypeEnum;
import org.spring.aicloud.service.IAnswerService;
import org.spring.aicloud.utils.MinIoUtil;
import org.spring.aicloud.utils.ResponseEntity;
import org.spring.aicloud.utils.SecurityUtil;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.stringtemplate.v4.ST;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.Wrapper;
import java.util.Base64;
import java.util.UUID;

/**
 * @author yexiebao
 * @date 2025/5/19
 */

@RestController
@RequestMapping("/tongyi")
public class TongyiController {
    @Resource
    private TongYiChatClient tongYiChatClient;
    @Resource
    private TongYiImagesClient tongYiImagesClient;
    @Resource
    private IAnswerService answerService;
    @Resource
    private MinIoUtil minIoUtil;
    /**
     * 聊天
     * @param question
     * @return
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) {
        if(!StringUtils.hasLength(question)){
            return ResponseEntity.error("请先输入内容!");
        }

        String result = tongYiChatClient.call(new Prompt(question))
                .getResult()
                .getOutput()
                .getContent();
        Answer answer  = new Answer();
        answer.setTitle(question);
        answer.setContent(result);
        answer.setModel(AIModelEnum.TONGYI.getCode());
        answer.setType(AITypeEnum.CHAT.getCode());
        answer.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean saveResult = answerService.save(answer);
        if (saveResult){
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.error("保存失败,请重试！");
    }
    /**
     * 绘图
     * @param question
     * @return
     */
    @RequestMapping("/draw")
    public ResponseEntity draw(String question) {

        if(!StringUtils.hasLength(question)){
            return  ResponseEntity.error("请先输入内容!");
        }

        //保存到minIO
        String imgUrl = "";
        try {
            // 获取 base64 编码字符串（去掉可能的前缀）
            String base64Str = tongYiImagesClient.call(new ImagePrompt(question))
                    .getResult()
                    .getOutput()
                    .getB64Json();
            if (base64Str.startsWith("data:image")) {
                //base64Str.indexOf(",") 找到逗号 , 的位置（也就是元信息和真正内容的分界点）；
                //substring(... + 1) 表示从逗号之后开始截取，即只留下 base64 纯数据部分。
                base64Str = base64Str.substring(base64Str.indexOf(",") + 1);
            }

            // 解码成字节流
            byte[] imageBytes = Base64.getDecoder().decode(base64Str);
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes)) {
                // 构造唯一文件名（加 .png 后缀更规范）
                String fileName = "tongyi-draw-" + UUID.randomUUID().toString().replace("-", "") + ".png";
                // 上传并获取图片链接
                imgUrl = minIoUtil.upload(fileName, inputStream, "image/png");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印错误堆栈，方便排查
            throw new RuntimeException("图片上传失败：" + e.getMessage(), e);
        }
        Answer answer  = new Answer();
        answer.setTitle(question);
        answer.setContent(imgUrl);
        answer.setModel(AIModelEnum.TONGYI.getCode());
        answer.setType(AITypeEnum.DRAW.getCode());
        answer.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean saveResult = answerService.save(answer);
        if (saveResult) {
            return ResponseEntity.ok(imgUrl);
        }
        return ResponseEntity.error("保存失败,请重试！");
    }

    /**
     * 获取对话历史记录
     * @return
     */
    @RequestMapping("/getchatlist")
    public ResponseEntity getchatlist() {
        Long uid =SecurityUtil.getCurrentUser().getUid();
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        queryWrapper.eq("type",AITypeEnum.CHAT.getCode());
        queryWrapper.eq("model",AIModelEnum.TONGYI.getCode());
        queryWrapper.orderByDesc("aid");
        return ResponseEntity.ok(answerService.list(queryWrapper));
    }

    /**
     * 获取绘图历史记录
     * @return
     */
    @RequestMapping("/getdrawlist")
    public ResponseEntity getdrawlist() {
        //条件查询
        Long uid = SecurityUtil.getCurrentUser().getUid();
        QueryWrapper<Answer>queryWrapper = new QueryWrapper();
        queryWrapper.eq("uid",uid)
                    .eq("type", AITypeEnum.DRAW.getCode())
                    .eq("model",AIModelEnum.TONGYI.getCode())
                    .orderByDesc("aid");
        return ResponseEntity.ok(answerService.list(queryWrapper));
    }
}
